<template>
  <div class="account-settings-info-view" :style="{ minHeight: `${layoutContentHeight - pageHeaderHeight - 24}px` }">
    <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
      <a-form-item :label="$t('platformManagement.app.loginByQr')">
        <a-switch
          :disabled="!canEdit"
          :checked="scanChecked"
          v-decorator="['scan', { initialValue: false }]"
          @change="checked => (scanChecked = checked)"
        />
      </a-form-item>
      <div v-show="form.getFieldValue('scan')">
        <a-form-item :label="$t('platformManagement.app.qrType')">
          <a-radio-group
            :disabled="!canEdit"
            v-decorator="[
              'openChat.type',
              {
                rules: [
                  { required: true, message: $t('common.emptyErr', { name: $t('platformManagement.app.qrType') }) }
                ]
              }
            ]"
          >
            <a-radio :value="1">{{ $t('modules.common.wechatWork') }}</a-radio>
            <a-radio :value="2" disabled>{{ $t('modules.common.dingding') }}</a-radio>
          </a-radio-group>
        </a-form-item>

        <div class="form-inner">
          <div v-show="form.getFieldValue('openChat.type') === 1">
            <a-form-item label="CorpID">
              <a-input
                :disabled="!canEdit"
                v-decorator="[
                  'openChat.corpId',
                  {
                    rules: [{ required: true, message: $t('common.emptyErr', { name: 'CorpId' }), whitespace: true }]
                  }
                ]"
              />
            </a-form-item>

            <a-form-item label="AgentId">
              <a-input
                :disabled="!canEdit"
                v-decorator="[
                  'openChat.agentId',
                  {
                    rules: [
                      {
                        required: true,
                        message: $t('common.emptyErr', { name: 'AgentId' }),
                        transform: val => val && val.trim()
                      },
                      { pattern: isAgentId, message: '请输入正确的AgentId' }
                    ]
                  }
                ]"
              />
            </a-form-item>

            <a-form-item label="SecretId">
              <a-input
                :disabled="!canEdit"
                v-decorator="[
                  'openChat.secretId',
                  {
                    rules: [{ required: true, message: $t('common.emptyErr', { name: 'SecretId' }), whitespace: true }]
                  }
                ]"
              />
            </a-form-item>

            <a-form-item class="relation-group" label="开通类型">
              <a-radio-group
                :disabled="!canEdit"
                name="radioGroup2"
                v-decorator="[
                  'openChat.linkBy',
                  {
                    rules: [{ required: true, message: '请选择开通类型' }]
                  }
                ]"
              >
                <a-radio value="username">通过账号关联</a-radio>
                <a-radio value="job_number">通过工号关联</a-radio>
                <a-radio value="telephone">通过手机关联</a-radio>
                <a-radio value="email">通过邮箱关联</a-radio>
              </a-radio-group>
            </a-form-item>
          </div>
          <div v-if="form.getFieldValue('scanType') === 2">
            <a-form-item label="dingdingID">
              <a-input :disabled="!canEdit" />
            </a-form-item>
          </div>
        </div>
      </div>

      <a-form-item :label="$t('platformManagement.app.loginByHid')">
        <a-switch
          :disabled="!canEdit"
          :checked="hidChecked"
          v-decorator="['hid', { initialValue: false }]"
          @change="checked => (hidChecked = checked)"
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 4 }">
        <a-button
          v-action:update
          type="primary"
          style="margin-left: 8px;"
          html-type="submit"
          :loading="comfirmLoading"
        >{{ $t('button.update') }}</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { saveSetting } from '@/api/company'
import { readLoginPageWays } from '@/api/auth'
import { isAgentId } from '@/utils/regExp'
import { layoutMixin } from '@/utils/mixin'

export default {
  name: 'LoginConfig',
  mixins: [layoutMixin],
  data () {
    return {
      isAgentId,
      form: this.$form.createForm(this),
      comfirmLoading: false,
      hidChecked: false,
      scanChecked: false,
      canEdit: this.$auth('update', this.$route.meta.permissionId)
    }
  },
  mounted () {
    this.getSetting()
  },
  methods: {
    async getSetting () {
      const res = await readLoginPageWays()
      if (res.code === 'sso.ok') {
        const { hid, scan, openChat } = res.data
        const fieldsValue = {
          hid,
          scan
        }
        if (scan) {
          const { agentId, corpId, secretId, linkBy, type } = openChat
          this.form.setFieldsValue({
            openChat
          })
        }
        this.form.setFieldsValue(fieldsValue)
        this.hidChecked = hid
        this.scanChecked = scan
      }
    },
    handleSubmit (e) {
      const { validateFields, getFieldsValue, getFieldValue } = this.form
      e.preventDefault()
      const fields = ['hid', 'scan']
      if (this.scanChecked) {
        const scanType = getFieldValue('openChat.type')
        if (scanType === 1) {
          const fieldsValue = getFieldsValue()
          const otherFields = Object.keys(fieldsValue.openChat).map(key => `openChat.${key}`)
          fields.push(...otherFields)
        } else {
          fields.push('openChat.type')
        }
      }
      validateFields(fields, async (err, values) => {
        if (!err) {
          this.comfirmLoading = true
          // 扫码配置
          if (values.scan) {
            for (const key in values.openChat) {
              if (['agentId', 'corpId', 'secretId'].includes(key)) {
                values.openChat[key] = values.openChat[key] ? values.openChat[key].trim() : ''
              }
            }
          } else {
            delete values.openChat
          }

          const res = await saveSetting(values)
          this.comfirmLoading = false
          if (res.code === 'sso.ok') {
            this.$message.success(res.message)
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.account-settings-info-view {
  .form-inner {
    padding-left: 70px;
  }
  /deep/ .ant-radio-wrapper {
    height: 39px;
    line-height: 39px;
  }
  .relation-group /deep/ .ant-radio-wrapper {
    display: block;
  }
}
</style>
